package com.fuyu.system.service.impl;

import com.fuyu.common.exception.AuthException;
import com.fuyu.common.model.TokenUserInfo;
import com.fuyu.common.utils.JwtUtil;
import com.fuyu.system.domain.SecurityUser;
import com.fuyu.system.domain.UserInfo;
import com.fuyu.system.models.form.SysLoginForm;
import com.fuyu.system.models.vo.login.LoginVO;
import com.fuyu.system.service.SysLoginService;
import com.fuyu.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;


@Slf4j
@Service
public class SysLoginServiceImpl implements SysLoginService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public LoginVO login(SysLoginForm params) {

        Authentication authenticate;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(params.getUsername(), params.getPassword());
            authenticate = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            throw new AuthException("账号密码错误");
        }

        boolean authenticated = authenticate.isAuthenticated();

        if (!authenticated) {
            log.error("\n{} 登入失败", params.getUsername());

            return null;

        }
        SecurityUser securityUser = (SecurityUser) authenticate.getPrincipal();

        UserInfo loginUser = securityUser.getLoginUser();


        String token = JwtUtil.createToken(TokenUserInfo.builder()
                .userId(loginUser.getUserId())
                .username(loginUser.getUsername())
                .build());

        LoginVO loginVO = LoginVO.builder()
                .accessToken(token)
                .build();

        return loginVO;
    }
}
